<?php

namespace common\model\sell66;

use common\db\Sell66;
use common\libs\StringHelper;

class User extends Sell66 {
	// 设置当前模型对应的完整数据表名称
	protected $table = 'user';
	protected $pk = 'user_id';
	const  DEFAULTCOUNT = 3;

    // 订单金额限制 1.审核中 0.正常
    public static $limitStatusMap = [
        'auditing' => 1,
        'success' => 0,
    ];

	public static function getSteamUser($userId) {
	}
	public static function createUserBySteam($steamUser, $user = array()) {
		$connection = (new self)->db();
		$connection->startTrans ();
		try {
			$userModel = new self ();
			if (! empty ( $user ['mobile'] )) {
				$userModel->mobile = $user ['mobile'];
			}
			if (! empty ( $user ['email'] )) {
				$userModel->email = $user ['email'];
			}
			if (! empty ( $user ['login_name'] )) {
				$userModel->login_name = $user ['login_name'];
			}

            $salt = date('YmdHis').mt_rand(1, 99999).uniqid();
            $userModel->invite_code = StringHelper::get62($salt);

            $userModel->login_time = time();
			if (! $userModel->save ()) {
				$connection->rollback();
				return false;
			}
			
			$userBalance = UserBalance::createUserBalance ( $userModel->user_id );
			if (empty ( $userBalance )) {
				$connection->rollback();
				return false;
			}
			
			$userSteam = UserSteam::createSteamUser ( $userModel->user_id, $steamUser );
			if (empty ( $userSteam )) {
				$connection->rollback();
				return false;
			}
            $connection->commit();
			return $userSteam;
		} catch (\Exception $e) {
			$connection->rollback();
			return false;
		}
	}
	public function usersteam() {
		return $this->hasOne ( 'UserSteam', 'user_id', 'user_id' );
	}
	
	/**
	 * 检验交易密码
	 */
	public static function getUsersByUserId($userId) {
		return self::where ( [
            'user_id' => $userId
        ] )->find ();
	}
	
	/**
	 * 检验交易密码
	 */
	public function checkIsSetTransPwd() {
		if (! empty ( $this->transaction_pwd )) {
			return true;
		}
		
		return false; // 交易密码未设置
	}
	
	/**
	 * 检验交易密码
	 */
	public function checkTransPwd($transPwd) {
		$transPwd = md5(md5($transPwd) . $this->transaction_salt);
		if ($transPwd == $this->transaction_pwd) {
			return true;
		}
		
		return false; // 交易密码错误
	}
	
	
	
	/**
	 * 设置交易密码
	 */
	public static function saveTransPwd($userId, $transPwd, $salt, $email) {
		return (new self)->save ( [
				'transaction_pwd' => $transPwd,
				'transaction_salt' => $salt,
                'email' => $email
		], [ 
				'user_id' => $userId 
		] );
	}

	/**
     * 获取用户信息
     */
	public static function getUserInfoByUserId($userId)
    {
        return self::where(['user_id'=>$userId])->field('mobile, email,invite_code, wallet_address')->find();
    }

    /**
     * 设置用户联系方式
     */
    public static function saveUserContact($userId, $email, $qq, $mobile)
    {
        $model = User::get($userId);
        $model->email = $email;
        $model->qq = $qq;
        $model->mobile = $mobile;
        return $model->save();
    }

    // 添加用户积分
    public static function addScoreByUserId($userId, $score)
    {
        $model = User::get($userId);
        $model->total_score = number_format($model->total_score + $score, 2, '.', '');
        $model->surplus_score = number_format($model->surplus_score + $score, 2, '.', '');
        $result = $model->save();
        if($result){
            return true;
        }else{
            return false;
        }
    }

    // 更改用户等级
    public static function saveUserLevel($userId, $level)
    {
        $model = User::get($userId);
        $model->level = $level;
        $model->save();
        return $model->toArray();
    }

    // 验证邮箱唯一
    public static function getUserByEmail($email)
    {
        return static::get(['email'=>$email]);
    }
    
    /**
     * 获取抽奖次数 
     * @param unknown $userId
     */
    public static function getRaffleCount($userId,$source){
    	$count = InviteLog::where(['from_user_id'=>$userId,'source'=>$source])->count();
    	return $count+self::DEFAULTCOUNT;
    }

    /**
     * 更新用户登录时间
     */
    public static function refreshLoginTimeByUserId($userId){
        return User::where(['user_id'=>$userId])->update(['login_time'=>time()]);
    }

    /**
     * 更新用户活动积分
     */
    public static function updateUserPoint($userId, $point)
    {
        $user = self::where(['user_id' => $userId])->find();
        $user->point += $point;
        if($point > 0){
            $user->his_point += $point;
        }
        return $user->save();
    }

    /**
     * 获取积分排行
     * @return array
     */
    public static function getTopPointDetails()
    {
        $result = static::alias('u')
            ->join('user_steam s', 'u.user_id = s.user_id')
            ->field('u.point,u.user_id,s.personaname,s.avatarmedium')
            ->where('u.point', '>', 0)
            ->limit(10)
            ->order('u.point desc')
            ->order('u.user_id asc')->select();

        return !empty($result) ? collection($result)->toArray() : array();
    }

    /**
     * 获取积分排行
     * @return array
     */
    public static function getUserTopPointRanking()
    {
        $result = static::alias('u')
            ->join('user_steam s', 'u.user_id = s.user_id')
            ->field('u.point,u.user_id,s.personaname,s.avatarmedium')
            ->where('u.point', '>', 0)
            ->order('u.point desc')
            ->order('u.user_id asc')->select();

        return !empty($result) ? collection($result)->toArray() : array();
    }

    /**
     * 检查是否是用户邀请码
     * @param string $inviteCode 邀请码
     * @return bool
     */
    public static function checkUserInviteCode($inviteCode)
    {
        $where = array(
            'invite_code' => $inviteCode,
        );

        $result = static::where($where)->field('user_id')->find();

        return !empty($result) ? $result->toArray() : array();
    }

    /**
     * 获取用户邀请码为空的用户数量
     * @param int $userId 用户ID
     * @return int
     */
    public static function getUsersNonInviteCodeNum($userId = NULL)
    {
        $where = array(
            'invite_code' => '',
        );

        if ($userId) {
            $where['user_id'] = $userId;
        }

        return static::where($where)->count();
    }

    /**
     * 获取用户邀请码为空的用户
     * @param int $userId 用户ID
     * @param int $page 分页
     * @param int $limit 页长
     * @return bool
     */
    public static function getUsersNonInviteCode($userId = '', $page = 1, $limit = 10)
    {
        $offset = ($page - 1) * $limit;

        $where = array();
        if ($userId) {
            $where['user_id'] = $userId;
        }

        $query = static::where($where);

        $result = $query->field('user_id, invite_code')->limit($offset, $limit)->select();

        return !empty($result) ? collection($result)->toArray() : array();
    }

    /**
     * 记录用户邀请码
     * @param int $userId 用户ID
     * @param string $inviteCode 邀请码
     * @return bool
     */
    public static function updateUsersInviteCode($userId, $inviteCode)
    {
        $where = array(
            'user_id' => $userId,
        );

        $field = array(
            'invite_code' => $inviteCode,
        );

        return static::where($where)->update($field);
    }

    /**
     * 修改用户订单金额限制状态
     * @param int $userId 用户ID
     * @param int $limitStatus 状态
     * @return bool
     */
    public static function updateUserLimitStatus($userId, $limitStatus)
    {
        $where = array(
            'user_id' => $userId,
        );

        $field = array(
            'limit_status' => $limitStatus,
        );

        return static::where($where)->update($field);
    }

    /**
     * 设置钱包地址
     */
    public static function saveWalletAddress($userId, $walletAddress)
    {
        $model = User::get($userId);
        $model->wallet_address = $walletAddress;
        return $model->save();
    }
}